package dynamiccompile;

import javax.tools.JavaCompiler;
import javax.tools.ToolProvider;
import java.io.*;
import java.lang.reflect.Method;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * 动态编译
 */
public class Demo01 {
    public static void main(String[] args) throws IOException {
        //获取动态编译器 Java编译器
        JavaCompiler compiler= ToolProvider.getSystemJavaCompiler();
        //输入流 输出流 错误输出流(报错信息) (java)文件地址
        int result=compiler.run(null,null,null,"C:\\Users\\lenovo\\Desktop\\Dynamic\\Hello.java");
        System.out.println(result==0?"编译成功":"编译失败");

        //动态运行:通过Runtime调用执行类
        Runtime run=Runtime.getRuntime();
        Process process=run.exec("java -cp C:\\Users\\lenovo\\Desktop\\Dynamic Hello");

        InputStream in=process.getInputStream();
        BufferedReader br=new BufferedReader(new InputStreamReader(in));
        String info="";
        while ((info=br.readLine())!=null){
            System.out.println(info);
        }

        //动态运行:通过反射调用main方法
        URL[] urls=new URL[]{new URL("file:\\"+"C:\\Users\\lenovo\\Desktop\\Dynamic\\")};
        URLClassLoader loader=new URLClassLoader(urls);
        try {
            Class c=loader.loadClass("Hello");
            Method method=c.getMethod("main",String[].class);
            method.invoke(null,(Object)new String[]{});

        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}
